<?php

$loader->requireOnce('includes/RadErrorCode.class.php');
$loader->requireOnce('includes/RadException.class.php');
$loader->requireOnce('includes/RadConnector/InPatientRadConnector.class.php');
$loader->requireOnce('includes/RadConnector/OutPatientRadConnector.class.php');
$loader->requireOnce('includes/RadConnector/RadConnectorFactory.class.php');
class C_Radiology extends Controller {
    private $logger ;

    function __construct($template_mod = "general") {
        parent::__construct($template_mod);
        $this->logger = LoggerManager::getLogger('module.dept_rad.controllers.C_Radiology');
        $this->template_mod = $template_mod;
        $this->view->path="radiology";
    }

    public function actionListAssignmentTicketAjax($ticketId = 0, $triggeredElement) {
        if (isset($_GET['ticketId'])) {
            $ticketId    =   $_GET['ticketId'];
        }
        $this->logger->info('Start action ListAssignmentTicketAjax');
        $assignmentList =   ORDataObject::factory('RadTicket')->getAssignmentsByTicket($ticketId);
        $options        =   $this->buildAssignmentList($assignmentList);
        $this->assign('ticketId', $ticketId);
        $this->assign('assigmentList', $options);
        $this->assign('triggeredElement', $triggeredElement);
        $this->logger->info('Finish action ListAssignmentTicketAjax');

        return $this->view->render('assignment_list.html');
    }

    private function buildAssignmentList($assignmentList) {
    	$list  =   array();
        foreach ($assignmentList as $assignment) {
            $name   =   '';
            $enumRadType    =   $assignment['enum_rad_type'];
            $localizedTypeName  =   Utils::getEnumTextByKey(EnumerationConstant::PARACLINIC_TYPE, $enumRadType);
            $time   =   explode(' ', $assignment['request_time']);
            $enumStatus =   $assignment['enum_ticket_status'];
            $status =   Utils::getEnumTextByKey(EnumerationConstant::RAD_TICKET_STATUS, $enumStatus);
            $list[$assignment['rad_ticket_id']] =   $this->buildAssignmentTicketName($assignment['enum_rad_type'], $assignment['request_time']) . " [$status]";
        }

        return $list;
    }

    public function actionGetAssignmentServicesAjax($radTicketId = 0) {
        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''), 'result'=>'');
    	if (isset($_GET['radTicketId'])) {
            $radTicketId   =   $_GET['radTicketId'];
        }
        $this->logger->info("Start action GetAssignmentServicesAjax {radTicketId=$radTicketId}");
        $objRadTicket   =   Celini::newORDO('RadTicket', $radTicketId);
        $ticketName     =   $this->buildAssignmentTicketName($objRadTicket->getEnumRadType(), $objRadTicket->getRequestTime());
        $doctorName     =   Celini::newORDO('Person', $objRadTicket->getTreatmentDoctorId())->getName();
        $diagnosis      =   $objRadTicket->getDiagnosis();
        $result['result']['ticketName'] =   $ticketName;
        $result['result']['doctorName'] =   $doctorName;
        $result['result']['diagnosis'] =    nl2br($diagnosis);
        $itemList    =   ORDataObject::factory('RadTicketItem')->getServicesByTicket($radTicketId);
        $html   =  $this->buildAssignmentItemList($itemList);
        $this->logger->info("Finish action GetAssignmentServicesAjax {radTicketId=$radTicketId}");
        $result['result']['service']   =   $html;

        return json_encode($result);
    }


    private function buildAssignmentTicketName($enumRadType, $requesTime) {
        $localizedTypeName  =   Utils::getEnumTextByKey(EnumerationConstant::PARACLINIC_TYPE, $enumRadType);
        $time   =   explode(' ', $requesTime);
        $name   =   $localizedTypeName . " " . $time[0];

        return $name;
    }

    private function buildAssignmentItemList($itemList){
        $html   =   "";
        foreach ($itemList as $item) {
            $html   .=  "<tr><td>" . $item['name'] . "</td>" .
                    "<td>" . $item['original_price'] . "</td>" .
                    "<td>" . $item['insurance_price'] . "</td>" .
                    "<td>" . $item['patient_price'] . "</td></tr>";
        }
        if (strlen($html)==0) {
        	$html  =   "<tr><td colspan='4'>" . _('There is no information on services of the ticket') . "</td></tr>";
        }

        return $html;
    }

    public function actionDeleteAssignmentTicketAjax($radTicketId = 0, $itemType = '') {
        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''), 'result'=>'');
    	if(isset($_GET['radTicketId'])) {
        	$radTicketId   =   $_GET['radTicketId'];
        }
        $this->logger->info("Start action DeleteAssignmentTicketAjax {radTicketId=$radTicketId}");
        try {
	        $objRadTicket       =   Celini::newORDO('RadTicket', $radTicketId);
	        // Check status of the assignment to be deleted
	        $ticketStatus   =   $objRadTicket->getEnumTicketStaus();
	        if ($ticketStatus == Utils::getEnumKey(EnumerationConstant::RAD_TICKET_STATUS,
	                    EnumerationConstant::RAD_TICKET_STATUS_INPROGRESS)
	            || $ticketStatus == Utils::getEnumKey(EnumerationConstant::RAD_TICKET_STATUS,
	                    EnumerationConstant::RAD_TICKET_STATUS_DONE)) {
	            throw new RadException("Could not delete rad assignment has status [" .
	                EnumerationConstant::RAD_TICKET_STATUS_INPROGRESS . "," .
	                EnumerationConstant::RAD_TICKET_STATUS_DONE. "]", RadErrorCode::STATUS_NOT_DELETED);
	        }

	        // Delete all rad_items of the assignment
	        ORDataObject::factory('RadTicketItem')->deleteServicesByTicket($radTicketId);

	        // Delete the ticket from the radiology queue
	        ORDataObject::factory('RadQueue')->deleteAssignmentTicket($radTicketId);

	        // Get some infomation to send to HIS after deleting the assignment.
	        $enumPatientType    =   $objRadTicket->getEnumPatientType();


	        // Delete the assignment ticket
	        $objRadTicket->delete($radTicketId);

	        // Get HIS deligator
	        $deligator =   RadConnectorFactory::createConnector($enumPatientType);
	        if ($enumPatientType == Utils::getEnumKey(EnumerationConstant::PATIENT_TYPE,
                    EnumerationConstant::PATIENT_TYPE_INPATIENT)) {
                $itemType   =   Utils::getEnumKey(EnumerationConstant::IN_TICKE_ITEM_ITEMTYPE,
                                    EnumerationConstant::IN_TICKE_ITEM_ITEMTYPE_RADIOLOGY);
            }
            // HIS: do needed tasks after deleting assignment
	        $deligator->doAfterDeleteAssignment($radTicketId, $itemType);
        }
        catch (EnumException $e) {
            $result['error']['code']    =   $e->getErrorCode();
            $result['error']['mess']    =   CoreErrorCode::getErrorMess($e->getErrorCode());
            $this->logger->error('DeleteAssignmentTicketAjax rad assignment [' . $radTicketId . '] fail. Error detail: '. $e->getMessage());
        }

        catch (RadException $e) {
            $result['error']['code'] = $e->getErrorCode();
            $result['error']['mess'] = RadErrorCode::getErrorMess($e->getErrorCode());
            $this->logger->error('DeleteAssignmentTicketAjax rad assignment [' . $radTicketId . '] fail. Error detail: '. $e->getMessage());
        }

        catch (Exception $e) {
            $result['error']['code'] = CoreErrorCode::COMMON_ERROR;
            $result['error']['mess'] = CoreErrorCode::getErrorMess(CoreErrorCode::COMMON_ERROR);
            $this->logger->error('DeleteAssignmentTicketAjax rad assignment [' . $radTicketId . '] fail. Error detail: '. $e->getMessage());
        }
        $this->logger->info("Finish action DeleteAssignmentTicketAjax {radTicketId=$radTicketId}");
        return json_encode($result);
    }
}
?>